// 上传图片

import SendUrl from './config.js'
const config = SendUrl.AllUrl

export function UpdataImg(file, callback) {
	var that = this
	var ImgArr = []
	uni.showLoading({
		title: '上传中...',
	})
	for (var i in file) {
		UpImgResolve(file[i], i).then((res) => {
			ImgArr.push(res.img)
			// 当需要上传的文件上传完，返回上传成功的数组
			if (ImgArr.length == file.length) {
				callback(ImgArr)
				uni.hideLoading();
			}

		})
	}
}

export function UpImgResolve(file, index) {
	return new Promise(function(resolve, reject) {
		uni.uploadFile({
			url: config + "upload/save-img",
			filePath: file,
			name: 'file',
			formData: {
				'file': file
			},
			success: function(uploadFileRes) {
				var date = {
					index: index,
					img: uploadFileRes.data
				}
				resolve(date)
			},
			error(res) {
				uni.hideLoading();
			}
		});
	})
}
// 封装获取到全局数据 -- 类型
export function GetType() {
	return new Promise(function(resolve, reject) {
		uni.request({
			url: config + "/battery/classify",
			data: {},
			method: "GET",
			dataType: 'json',
			header: {
				'content-type': 'application/json;charset=UTF-8',
				"Authorization": uni.getStorageSync("token") || ''
			},
			success: (res) => {
				if (res.data.code == 200) {
					resolve(res);
				} else {
					uni.showToast({
						title: res.data.msg,
						mask: true,
						icon: "none",
						duration: 1000
					})
					reject(res.data.msg);
				}
			},
			fail: (err) => {
				uni.hideLoading();
				reject(err)
			}
		})
	})
}
// --- 获取品牌
export function GetBrand() {
	return new Promise(function(resolve, reject) {
		uni.request({
			url: config + "/battery/brand",
			data: {},
			method: "GET",
			dataType: 'json',
			header: {
				'content-type': 'application/json;charset=UTF-8',
				"Authorization": uni.getStorageSync("token") || ''
			},
			success: (res) => {
				if (res.data.code == 200) {
					resolve(res);
				} else {
					uni.showToast({
						title: res.data.msg,
						mask: true,
						icon: "none",
						duration: 1000
					})
					reject(res.data.msg);
				}
			},
			fail: (err) => {
				uni.hideLoading();
				reject(err)
			}
		})


	})
}
// --- 获取型号
export function GetModel() {
	return new Promise(function(resolve, reject) {
		uni.request({
			url: config + "/battery/battery/model",
			data: {},
			method: "GET",
			dataType: 'json',
			header: {
				'content-type': 'application/json;charset=UTF-8',
				"Authorization": uni.getStorageSync("token") || ''
			},
			success: (res) => {
				if (res.data.code == 200) {
					resolve(res);
				} else {
					uni.showToast({
						title: res.data.msg,
						mask: true,
						icon: "none",
						duration: 1000
					})
					reject(res.data.msg);
				}
			},
			fail: (err) => {
				uni.hideLoading();
				reject(err)
			}
		})


	})
}

// 扫码入口
export function scanCode(callback) {
	uni.scanCode({
		success: function(res) {
			callback(res.result)
		}
	});
}


// export function getLiveTimeCount(time,mins){
// 	   var date = ''
// 	   myTotaltime(time,mins,res=>{
// 	   		 date = res
// 	   })
// 	   setInterval(function(){
// 		   if(date != ''){
// 			   return date
// 		   }
// 	   },500)

// }


export function getLiveTimeCount(time, mins, callback) {
	if (time) { //如果设置了开始时间
		// 生成当前时间增加的分钟量
		var curTime = new Date(time);
		var liveCountdown = ''
		this.liveCountTimes = setInterval(() => {
			//注：不论安卓还是ios，请将时间如 2020-02-02 20:20:20 转化为 2020/02/02 20:20:20 这种形式后再使用，否则无法转换，如下转换即可↓
			// let transedPreTime=curTime.replace(/-/g,'/') //这里转化时间格式为以/分隔形式
			let nowTime = new Date().getTime();
			let preTime = new Date(curTime).getTime() + mins * 60 * 1000
			let obj = null;

			if (preTime - nowTime > 0) {
				let time = (preTime - nowTime) / 1000;
				let day = parseInt(time / (60 * 60 * 24));
				let hou = parseInt(time % (60 * 60 * 24) / 3600);
				let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
				let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
				obj = {
					day: day < 10 ? '0' + day : day,
					hou: hou < 10 ? '0' + hou : hou,
					min: min < 10 ? '0' + min : min,
					sec: sec < 10 ? '0' + sec : sec
				};
				liveCountdown = obj.day + '天' + obj.hou + '时' + obj.min + '分' + obj.sec + '秒'

				callback(liveCountdown)

			} else {
				// obj = {day:'00',hou:'00',min:'00',sec:'00'};
				// liveCountdown=obj.day + '天' + obj.hou + '时' + obj.min + '分' + obj.sec + '秒'
				liveCountdown = "已过期"
				callback(liveCountdown)
				clearInterval(this.liveCountTimes)
			}
		}, 1000)

	} else {
		liveCountdown = "已过期"
		callback(liveCountdown)
	}
}
// 一维数组转二维
export function changeArr(arr, length) {
	let len = arr.length;
	let lineNum = len % length === 0 ? len / length : Math.floor((len / length) + 1);
	let res = [];
	for (let i = 0; i < lineNum; i++) {
		// slice() 方法返回一个从开始到结束（不包括结束）选择的数组的一部分浅拷贝到一个新数组对象。且原始数组不会被修改。
		let temp = arr.slice(i * length, i * length + length);
		res.push(temp)
	}
	return res

}
// 收藏
export function Collection(_this, id, type) {
	var url = ''
	if (type == 1) {
		url = _this.$Api.CancelCollect
	} else {
		url = _this.$Api.Collect
	}
	var data = {
		"userId": uni.getStorageSync("userId") || '8880202106210000028',
		"newsId": id
	}
	return new Promise(function(resolve, reject) {
		uni.request({
			url: config + url,
			data: data,
			method: "POST",
			dataType: 'json',
			header: {
				// 'content-type': 'application/json;charset=UTF-8',
				// "Authorization": uni.getStorageSync("token") || ''
			},
			success: (res) => {
				if (res.data.code == 200) {
					resolve(res);
				} else {
					uni.showToast({
						title: res.data.msg,
						mask: true,
						icon: "none",
						duration: 1000
					})
					reject(res.data.msg);
				}
			},
			fail: (err) => {
				uni.hideLoading();
				reject(err)
			}
		})


	})
}

// 点赞
export function zanTaps(_this, id, type) {
	var url = ''
	if (type == 1) {
		url = _this.$Api.CancelLike
	} else {
		url = _this.$Api.Like
	}
	var data = {
		"userId": uni.getStorageSync("userId") || '8880202106210000028',
		"newsId": id
	}
	return new Promise(function(resolve, reject) {
		uni.request({
			url: config + url,
			data: data,
			method: "POST",
			dataType: 'json',
			header: {
				// 'content-type': 'application/json;charset=UTF-8',
				// "Authorization": uni.getStorageSync("token") || ''
			},
			success: (res) => {
				if (res.data.code == 200) {
					resolve(res);
				} else {
					uni.showToast({
						title: res.data.msg,
						mask: true,
						icon: "none",
						duration: 1000
					})
					reject(res.data.msg);
				}
			},
			fail: (err) => {
				uni.hideLoading();
				reject(err)
			}
		})


	})
}


export function withData(param) {
	return param < 10 ? '0' + param : '' + param;
}
export function getLoopArray(start, end) {
	var start = start || 0;
	var end = end || 1;
	var array = [];
	for (var i = start; i <= end; i++) {
		array.push(withData(i));
	}
	return array;
}

export function getMonthDay(year, month) {
	var flag = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0),
		array = null;

	switch (month) {
		case '01':
		case '03':
		case '05':
		case '07':
		case '08':
		case '10':
		case '12':
			array = getLoopArray(1, 31)
			break;
		case '04':
		case '06':
		case '09':
		case '11':
			array = getLoopArray(1, 30)
			break;
		case '02':
			array = flag ? getLoopArray(1, 29) : getLoopArray(1, 28)
			break;
		default:
			array = '月份格式不正确，请重新输入！'
	}
	return array;
}

export function getNewDateArry() {
	// 当前时间的处理 年月日时分秒
	var newDate = new Date();
	var year = withData(newDate.getFullYear()),
		mont = withData(newDate.getMonth() + 1),
		date = withData(newDate.getDate()),
		hour = withData(newDate.getHours()),
		minu = withData(newDate.getMinutes());
	// seco = withData(newDate.getSeconds());

	return [year, mont, date, hour, minu];
}
export function dateTimePicker(startYear, endYear, date) {
	// 返回默认显示的数组和联动数组的声明
	var dateTime = [],
		dateTimeArray = [
			[],
			[],
			[]
		];
	var start = startYear || 1978;
	var end = endYear || 2100;

	//处理传过来的字符串转化为数组
	let dataArr = date.split(" ")[0].split('/')
	let time = date.split(" ")[1].split(':')
	// 默认开始显示数据 如果把自定义值传过来的话就使用自定义时间 否则用当前时间  ...dataArr数组解构
	var defaultDate = date ? [...dataArr, ...time] : getNewDateArry();

	// 处理联动列表数据
	/*年月日 时分秒*/
	dateTimeArray[0] = getLoopArray(start, end);
	dateTimeArray[1] = getLoopArray(1, 12);
	dateTimeArray[2] = getMonthDay(defaultDate[0], defaultDate[1]);
	// dateTimeArray[3] = getLoopArray(0, 23);
	// dateTimeArray[4] = getLoopArray(0, 59);
	// dateTimeArray[5] = getLoopArray(0, 59);

	//遍历dateTimeArray数组
	dateTimeArray.forEach((current, index) =>
		//匹配defaultDate[index]值在current数组中的位置
		dateTime.push(current.indexOf(defaultDate[index]))
	);

	return {
		dateTimeArray: dateTimeArray,
		dateTime: dateTime
	}
}

// 判断数组对象是否用空值
export function judgeListComplete(list) {
	let isNotComplete = list.findIndex(item => {
		return judgeObjectComplete(item) === false
	})
	if (isNotComplete > -1) {
		return false
	} else {
		return true
	}
}

export function judgeObjectComplete(ObjectValue) {
	let flag = new Boolean()
	flag = true
	for (let key in ObjectValue) {
		if (ObjectValue[key] || ObjectValue[key] === 0) {} else {
			flag = false
		}
	}
	if (!flag) {
		return false
	} else {
		return true
	}
}
// 防抖节流
export function debounce(fn, delay) {

	if (this.timeout !== null) clearTimeout(this.timeout)
	this.timeout = setTimeout(() => {
		//做的事情
	}, delay)
}
// 剩余几个月
export function monDiff(startTime, endTime, type) {
	startTime = new Date(startTime)

	endTime = new Date(endTime)

	var dateToMonth = 0

	var startDate = startTime.getDate() + startTime.getHours() / 24 + startTime.getMinutes() / 24 / 60;

	var endDate = endTime.getDate() + endTime.getHours() / 24 + endTime.getMinutes() / 24 / 60;

	if (endDate >= startDate) {
		undefined

		dateToMonth = 0

	} else {
		undefined

		dateToMonth = -1

	}

	let yearToMonth = (endTime.getYear() - startTime.getYear()) * 12

	let monthToMonth = endTime.getMonth() - startTime.getMonth()

	return yearToMonth + monthToMonth + dateToMonth


}


// 计算剩余天数 <==> 日期时间 1 日期转剩余天数 2 转日期
export function ChangeDate(date, type) {
	if (date == '' || date == undefined || date == null) {
		return
	}
	if (type == 1) {
		var s1 = date
		s1 = new Date(s1);
		var s2 = new Date(); //当前日期：2017-04-24
		var time = s1.getTime() - s2.getTime()
		let obj = null;
		// var time = parseInt(days / (1000 * 60 * 60 * 24));\
		time = time / 1000;
		let day = parseInt(time / (60 * 60 * 24));
		let hou = parseInt(time % (60 * 60 * 24) / 3600);
		let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
		let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
		// let day = parseInt(time / (1000 * 60 * 60 * 24));
		// let hou = parseInt(time % (60 * 60 * 24) / 3600);
		// let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
		// let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
		obj = {
			day: day < 10 ? '0' + day : day,
			hou: hou < 10 ? '0' + hou : hou,
			min: min < 10 ? '0' + min : min,
			sec: sec < 10 ? '0' + sec : sec
		};

		if (time > 0) {
			return obj.day + '天' + obj.hou + '时' + obj.min + '分' + obj.sec + '秒'
		} else {
			return "已过期"
		}
	} else if (type == 2) {
		var s1 = date
		s1 = new Date(s1);
		var s2 = new Date(); //当前日期：2017-04-24
		var days = s1.getTime() - s2.getTime()
		var time = parseInt(days / (1000 * 60 * 60 * 24));
		if (days >= 0) {
			return true
		} else {
			return false
		}
	} else {
		const end = new Date();
		end.setTime(end.getTime() + 3600 * 1000 * 24 * date);
		return end
	}
}



export default {
	UpdataImg,
	GetType,
	GetBrand,
	scanCode,
	GetModel,
	getLiveTimeCount,
	changeArr,
	Collection,
	zanTaps,
	dateTimePicker,
	getMonthDay,
	judgeListComplete,
	judgeObjectComplete,
	debounce,
	monDiff,
	ChangeDate
}
